<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="JVM,">










<meta name="description" content="前面已经初步实现了线程私有的运行时数据区，主要包括操作数栈和局部变量表。接下来将继续丰富运行时数据区的内容——线程共享的运行时数据区，包括方法区和运行时常量池。本节的代码集中在 heap 包下。同时也会对一些概念做出解释。因为自己之前在这些概念上的错误认识，走了很多弯路。">
<meta name="keywords" content="JVM">
<meta property="og:type" content="article">
<meta property="og:title" content="手写JVM系列(11)-线程共享的运行时数据">
<meta property="og:url" content="https://zachaxy.github.io/2018/01/03/手写JVM系列-11-线程共享的运行时数据/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="前面已经初步实现了线程私有的运行时数据区，主要包括操作数栈和局部变量表。接下来将继续丰富运行时数据区的内容——线程共享的运行时数据区，包括方法区和运行时常量池。本节的代码集中在 heap 包下。同时也会对一些概念做出解释。因为自己之前在这些概念上的错误认识，走了很多弯路。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-01T11:13:24.302Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="手写JVM系列(11)-线程共享的运行时数据">
<meta name="twitter:description" content="前面已经初步实现了线程私有的运行时数据区，主要包括操作数栈和局部变量表。接下来将继续丰富运行时数据区的内容——线程共享的运行时数据区，包括方法区和运行时常量池。本节的代码集中在 heap 包下。同时也会对一些概念做出解释。因为自己之前在这些概念上的错误认识，走了很多弯路。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2018/01/03/手写JVM系列-11-线程共享的运行时数据/">





  <title>手写JVM系列(11)-线程共享的运行时数据 | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2018/01/03/手写JVM系列-11-线程共享的运行时数据/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">手写JVM系列(11)-线程共享的运行时数据</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-03T16:42:03+08:00">
                2018-01-03
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  2,897
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <blockquote>
<p>前面已经初步实现了线程私有的运行时数据区，主要包括操作数栈和局部变量表。接下来将继续丰富运行时数据区的内容——线程共享的运行时数据区，包括方法区和运行时常量池。本节的代码集中在 <a href="https://github.com/zachaxy/JVM/tree/master/Java/src/runtimedata/heap" target="_blank" rel="noopener">heap</a> 包下。同时也会对一些概念做出解释。因为自己之前在这些概念上的错误认识，走了很多弯路。</p>
</blockquote>
<a id="more"></a>

<h1 id="方法区"><a href="#方法区" class="headerlink" title="方法区"></a>方法区</h1><p>之前我们已经可以找到 class 文件，并把其内容加载到内存中，对其解析成一个 ClassFile 的结构，但是 ClassFile 中的内容仍然无法直接在方法区使用，还需要进一步的转换。其实转换的内容不多，我们通过代码来直观的对已一下 ClassFile 和 Zclass 中的区别。(为避免和 JDK 中已有的类名冲突，这里将我们自定义的 <code>class</code>，<code>method</code>，<code>field</code> 等前面都加一个 <code>z</code> 以作区分。)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Zclass</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> accessFlags;        <span class="comment">// 表示当前类的访问标志</span></span><br><span class="line">    <span class="keyword">public</span> String thisClassName;   <span class="comment">//当前类名字(完全限定名)</span></span><br><span class="line">    <span class="keyword">public</span> String superClassName;  <span class="comment">//父类名字(完全限定名)</span></span><br><span class="line">    <span class="keyword">public</span> String[] interfaceNames;<span class="comment">//接口名字(完全限定名,不可以为null,若为实现接口,数组大小为0)</span></span><br><span class="line">    <span class="keyword">private</span> RuntimeConstantPool runtimeConstantPool;<span class="comment">//运行时常量池,注意和class文件中常量池区别;</span></span><br><span class="line">    Zfield[] fileds;        <span class="comment">//字段表,包括静态和非静态，此时并不分配 slotId；下面的staticVars 是其子集</span></span><br><span class="line">    Zmethod[] methods;      <span class="comment">//方法表，包括静态和非静态</span></span><br><span class="line">    ZclassLoader loader;    <span class="comment">//类加载器</span></span><br><span class="line">    Zclass superClass;      <span class="comment">//当前类的父类class,由类加载时,给父类赋值;</span></span><br><span class="line">    Zclass[] interfaces;    <span class="comment">//当前类的接口class,由类加载时,给父类赋值;</span></span><br><span class="line">    <span class="keyword">int</span> instanceSlotCount;  <span class="comment">//非静态变量占用slot大小,这里只是统计个数(从顶级父类Object开始算起)</span></span><br><span class="line">    <span class="keyword">int</span> staticSlotCount;    <span class="comment">// 静态变量所占空间大小</span></span><br><span class="line">    Slots staticVars;      <span class="comment">// 存放静态变量</span></span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClassFile</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> minorVersion;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> majorVersion;</span><br><span class="line">    <span class="keyword">public</span> ConstantPool constantPool;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> accessFlags;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> thisClass;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> superClass;         <span class="comment">//同 thisClass 的索引值。</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span>[] interfaces;     <span class="comment">//存放所实现的接口在常量池中的索引。同 thisClass 的索引值。</span></span><br><span class="line">    <span class="keyword">private</span> MemberInfo[] fields;    <span class="comment">//存放类中所有的字段，包括静态的非静态的；不同的属性通过字段的访问修饰符来读取；</span></span><br><span class="line">    <span class="keyword">private</span> MemberInfo[] methods;   <span class="comment">//存放类中所有的方法，包括静态的非静态的；不同的属性通过方法的访问修饰符来读取；</span></span><br><span class="line">    <span class="keyword">private</span> AttributeInfo[] attributes; <span class="comment">//属性表，存放类的属性；</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对比由 ClassFile -&gt; Zclass 的转换可以发现：eg：ClassFile 中  superClass 的值是一个 int 的索引值，其指向常量池的一个常量，该常量由通过一个索引指向常量池中的 utf8-constant，从而用来表示当前 class 的父类的名字(字符串)。而在 Zclass 中，可以看到有一个 superClass 的成员变量，其类型为 Zclass 类型，而不再是简单的字符串。再来看在类中定义的成员变量，在 ClassFile 中成员变量是保存在MemberInfo 中，这也是简单的字符描述(变量类型，变量名字),在 Zclass 中保存的是新定义的 Zfield 类型的变量，这些都是需要转换的地方。</p>
<p>所以转换的本质是什么：<br>** class 文件中全是字符串，而现在加载到内存中了，就不能简单的用一个字符串来描述了，而是一个指向内存的一个实体**</p>
<p>所以针对于 ClassFile 到 Zclass 的转换，具体要转换的有三部分：</p>
<ul>
<li>类信息本身，这里定义为 Zclass</li>
<li>字段信息，这里定义为 Zfield，表示在类中定义的变量(静态+非静态)，Zfield 中有一个成员变量 Zclass，表明当前字段属于哪个类</li>
<li>方法信息，这里定义为 Zmethod，表示在类中定义的方法(静态+非静态)，Zmethod 中有一个成员变量 Zclass，表明当前方法属于哪个类</li>
</ul>
<p>而转换为 Zclass 的类，就是放在方法区的，其实叫方法区是有干扰的，让人以为方法区只是存放类中的方法的，并不是这样的。方法区存放的是一个 class 文件的描述，包括该类的权限，该类实现了哪些接口，该类的父类是谁，该类有哪些字段，以及字段的权限，该类有哪些方法，以及方法的权限等。<br>在本 JVM 中，方法区的实现是使用了一个 HashMap，其中 key 的 class 的全限定名，value 为加载进来的 zclass 对象。</p>
<p>读完上面的描述，你可能还是一头雾水，暂时先放到一边，因为单将方法区无法将清楚，其还要配合下面的运行时常量，才能查看其全貌。</p>
<h1 id="运行时常量池"><a href="#运行时常量池" class="headerlink" title="运行时常量池"></a>运行时常量池</h1><p>常量池，这个概念之前就遇到过，那是在解析 class 文件时，class 文件中就有一个常量池的概念，现在又遇到了常量池，不过不是一回事。</p>
<p>这里再次解释一下 class 文件中的常量池的概念。我们将 java 代码通过 javac 编译为 class 文件，接下来再运行 java 程序的时候就完全不需要 java 文件了，只需要 class 文件即可，但是 class 文件是保存在本地磁盘上的文件，里面全是0101的字节码，或者说是字符串，那各个字符串之间如何产生联系呢？那就是通过常量池，并给常量池安排了序号，每个序号都对应一个常量(字符串)，然后 class 文件规定了一个格式，每个 class 文件都要按照一定的次序排放，类名，访问权限，成员变量，成员方法等(具体可回顾<a href="https://zachaxy.github.io/2017/05/09/%E6%89%8B%E5%86%99JVM%E7%B3%BB%E5%88%97-4-%E5%88%86%E6%9E%90class%E6%96%87%E4%BB%B6/">分析class文件</a>)。如何描述类名，成员变量，成员方法？就是在 class 文件中对应的位置保存一个整数，用来指向 class 文件中另一块区域——常量池中的一个常量(字符串)，用字符串来描述这是什么。<br>在强调一遍：class 文件是在本地磁盘上的文件，其内部是死的。</p>
<p>那么接下来将 class 文件读到内存中，其常量池也要进行相应的转换。如果是基本类型的常量那么原封不动，但如果表示的是一个类的引用，在 class 文件中使用的还是字符串，用来说明是哪个类，而在运行期间，就要真正的加载这个类(保存在方法区)，然后指向加载的这个类，而不是之前简单的字符串了。</p>
<p>到这里，应该对两个常量池的作用有一个清楚的了解，自己之前就是把两个常量池当成一个，直接拿来用了！所以在描述常量池时，我会用 <code>class 文件中的常量池</code> 和 <code>运行时常量池</code> 来做区分。</p>
<p>所以，相对于 class 文件中的常量池，运行时常量池是在内存中的，是活的。由 class 文件中的常量池向运行时常量池的转换如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//主要作用是将class文件中的常量池转换为运行时常量池;</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">RuntimeConstantPool</span><span class="params">(Zclass clazz, ConstantPool classFileConstantPool)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.clazz = clazz;</span><br><span class="line">    ConstantInfo[] classFileConstantInfos = classFileConstantPool.getInfos();</span><br><span class="line">    <span class="keyword">int</span> len = classFileConstantInfos.length;</span><br><span class="line">    <span class="keyword">this</span>.infos = <span class="keyword">new</span> RuntimeConstantInfo[len];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; len; i++) &#123;</span><br><span class="line">        ConstantInfo classFileConstantInfo = classFileConstantInfos[i];</span><br><span class="line">        <span class="keyword">switch</span> (classFileConstantInfo.getType()) &#123;</span><br><span class="line">            <span class="keyword">case</span> ConstantInfo.CONSTANT_Integer:</span><br><span class="line">                ConstantIntegerInfo intInfo = (ConstantIntegerInfo) classFileConstantInfo;</span><br><span class="line">                <span class="keyword">this</span>.infos[i] = <span class="keyword">new</span> RuntimeConstantInfo&lt;Integer&gt;(intInfo.getVal(), ConstantInfo.CONSTANT_Integer);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> ConstantInfo.CONSTANT_Float:</span><br><span class="line">                ConstantFloatInfo floatInfo = (ConstantFloatInfo) classFileConstantInfo;</span><br><span class="line">                <span class="keyword">this</span>.infos[i] = <span class="keyword">new</span> RuntimeConstantInfo&lt;Float&gt;(floatInfo.getVal(), ConstantInfo.CONSTANT_Float);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> ConstantInfo.CONSTANT_Long:</span><br><span class="line">                <span class="comment">//Long 和 Double 在转换结束之后，都要进行 i++,以适配 class 文件中常量池的索引</span></span><br><span class="line">                ConstantLongInfo longInfo = (ConstantLongInfo) classFileConstantInfo;</span><br><span class="line">                <span class="keyword">this</span>.infos[i] = <span class="keyword">new</span> RuntimeConstantInfo&lt;Long&gt;(longInfo.getVal(), ConstantInfo.CONSTANT_Long);</span><br><span class="line">                i++;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> ConstantInfo.CONSTANT_Double:</span><br><span class="line">                ConstantDoubleInfo doubleInfo = (ConstantDoubleInfo) classFileConstantInfo;</span><br><span class="line">                <span class="keyword">this</span>.infos[i] = <span class="keyword">new</span> RuntimeConstantInfo&lt;Double&gt;(doubleInfo.getVal(), ConstantInfo.CONSTANT_Double);</span><br><span class="line">                i++;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> ConstantInfo.CONSTANT_String:</span><br><span class="line">                <span class="comment">//在对字符串引用进行转换的时候，转为字符串直接引用</span></span><br><span class="line">                ConstantStringInfo stringInfo = (ConstantStringInfo) classFileConstantInfo;</span><br><span class="line">                <span class="keyword">this</span>.infos[i] = <span class="keyword">new</span> RuntimeConstantInfo&lt;String&gt;(stringInfo.getString(), ConstantInfo.CONSTANT_String);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> ConstantInfo.CONSTANT_Class:</span><br><span class="line">                ConstantClassInfo classInfo = (ConstantClassInfo) classFileConstantInfo;</span><br><span class="line">                <span class="comment">//ref 类中真正需要的是 传入上面的 clazz</span></span><br><span class="line">                <span class="keyword">this</span>.infos[i] = <span class="keyword">new</span> RuntimeConstantInfo&lt;ClassRef&gt;(<span class="keyword">new</span> ClassRef(<span class="keyword">this</span>, classInfo), ConstantInfo.CONSTANT_Class);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> ConstantInfo.CONSTANT_Fieldref:</span><br><span class="line">                ConstantFieldRefInfo fieldRefInfo = (ConstantFieldRefInfo) classFileConstantInfo;</span><br><span class="line">                <span class="keyword">this</span>.infos[i] = <span class="keyword">new</span> RuntimeConstantInfo&lt;FieldRef&gt;(<span class="keyword">new</span> FieldRef(<span class="keyword">this</span>, fieldRefInfo), ConstantInfo.CONSTANT_Fieldref);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> ConstantInfo.CONSTANT_Methodref:</span><br><span class="line">                ConstantMethodRefInfo methodRefInfo = (ConstantMethodRefInfo) classFileConstantInfo;</span><br><span class="line">                <span class="keyword">this</span>.infos[i] = <span class="keyword">new</span> RuntimeConstantInfo&lt;MethodRef&gt;(<span class="keyword">new</span> MethodRef(<span class="keyword">this</span>, methodRefInfo), ConstantInfo.CONSTANT_Methodref);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> ConstantInfo.CONSTANT_InterfaceMethodref:</span><br><span class="line">                ConstantInterfaceMethodRefInfo interfaceMethodRefInfo = (ConstantInterfaceMethodRefInfo) classFileConstantInfo;</span><br><span class="line">                <span class="keyword">this</span>.infos[i] = <span class="keyword">new</span> RuntimeConstantInfo&lt;InterfaceMethodRef&gt;(<span class="keyword">new</span> InterfaceMethodRef(<span class="keyword">this</span>, interfaceMethodRefInfo), ConstantInfo.CONSTANT_InterfaceMethodref);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">                <span class="comment">//还有一些jdk1.7才开始支持的动态属性,不在本虚拟机的实现范围内</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里主要是对以下四种常量进行转换：</p>
<ul>
<li>类符号引用</li>
<li>字段符号引用</li>
<li>方法符号引用</li>
<li>接口方法符号引用</li>
</ul>
<p>这里再区分一个概念，拿字段符号引用来说，什么是字段符号引用，和上面讲到的方法区中要转换的字段又有什么关系？<br>以下面一个简单的例子说明：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span></span>&#123;</span><br><span class="line">    String str;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f</span><span class="params">()</span></span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"xxx"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个例子中 str 就是之前方法区要转换的字段。System.out 是字段符号引用,因为该 out 字段并非类 A 中定义的，而是在 System 类中定义的。</p>
<p>二者相同点：都是字段，那么是字段就要有字段名，类型，所在的类</p>
<p>不同的是：<br>方法区要转换的字段，是在当前类声明的成员变量，所以其所在的类就是当前类。<br>字段引用：FieldRef 类没有直接的一个字段指向其所在的类，而是有一个所在类的名字，那么在使用字段引用(FieldRef)时这就需要以下两步解决：</p>
<ul>
<li>用类加载器根据类名将对应的类加载进来</li>
<li>在从上一步加载到的类中，查找其定义的对应的字段，从而获取到真正的字段</li>
</ul>
<p>是在方法中的 code 属性中用到的。f 方法对应的字节码为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">0 getstatic #2 &lt;java/lang/System.out&gt;</span><br><span class="line">3 invokevirtual #3 &lt;java/io/PrintStream.println&gt;</span><br><span class="line">6 return</span><br></pre></td></tr></table></figure>

<p>其中的 getstatic 指令，后跟的索引2，指向的就是运行时常量池中的一个字段引用。那么 getstatic 指令要做的是从运行时常量池获取到一个 FieldRef，然后根据其类名加载类——System，因为 out 是类 System 中定义的一个变量，所以从 System 的 filed[] 数组中根据字段名找到对应的字段 field，<br>最后将该 field 压入操作数栈。</p>
<p>在上面的 invokevirtual 指令中，其后跟的索引3指向的是运行时常量池中的一个方法引用(MethodRef)，其方法名为println，该方法在 java/io/PrintStream 中定义，也就是 System.out 的类型。和字段引用解析类似，也是先加载其所在的类java/io/PrintStream到方法区，然后根据方法名找到对应的方法，最重要的是拿到方法中的 code 字节码，从而进行该方法的调用！</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>这一节主要介绍了线程共享的运行时数据区，该数据区包含两个重要的概念：方法区和运行时常量池。同时还着重强调了两组概念：</p>
<ul>
<li>class 文件中的常量池 和 运行时常量池</li>
<li>类中定义的字段、方法 和 字段引用，方法引用</li>
</ul>


    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2018/01/03/手写JVM系列-11-线程共享的运行时数据/" title="手写JVM系列(11)-线程共享的运行时数据">https://zachaxy.github.io/2018/01/03/手写JVM系列-11-线程共享的运行时数据/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/JVM/" rel="tag"># JVM</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2017/12/13/Groovy与DSL/" rel="next" title="Groovy与DSL">
                <i class="fa fa-chevron-left"></i> Groovy与DSL
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2018/01/04/手写JVM系列-12-类加载器的实现/" rel="prev" title="手写JVM系列(12)-类加载器的实现">
                手写JVM系列(12)-类加载器的实现 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#方法区"><span class="nav-number">1.</span> <span class="nav-text">方法区</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#运行时常量池"><span class="nav-number">2.</span> <span class="nav-text">运行时常量池</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">3.</span> <span class="nav-text">总结</span></a></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
